package com.storyroad.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONException;
import org.json.JSONObject;

import com.storyroad.utils.DBConnection;
import com.storyroad.utils.TableNames;
import com.storyroad.utils.Utilities;

/**
 * Servlet implementation class UpdateStory
 */
public class UpdateStory extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UpdateStory() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * Edits an already existing  story fragment. Only the owner of the fragment is allowed to carry out this
     * operation.
	 * @param request HttpServletRequest object that contains data coming from front-end
	 * @param response HttpServletResponse object that contains data which is prepared after processing the incoming data
     * @throws ServletException
     * @throws IOException
     */
    protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");

		String f_requestType = request.getParameter("request_type");
		if (f_requestType == null || !f_requestType.equals("Android")) {
			f_requestType = "Web";
		}
		
		// Title, body, location description and the coordinates of the location can be changed.
		int story_id = Integer.parseInt(request.getParameter("story_id"));
		String f_title = Utilities.convertToEnglish(request.getParameter("title"));
		String f_body = Utilities.convertToEnglish(request.getParameter("body"));
		String f_locationDescription = Utilities.convertToEnglish(request.getParameter("location"));
		String f_coordinates = request.getParameter("coordinates");
		double f_locationX = Double.parseDouble(f_coordinates.split(",")[0]);
		double f_locationY = Double.parseDouble(f_coordinates.split(",")[1]);
		
		PreparedStatement stmt = null;
		String sqlStatement = null;
		Connection conn = new DBConnection().connect();
		PrintWriter out = response.getWriter();
		
		if (conn == null) {
			out.println("Connection error");
		} else {
			try {
				String username;
				if (f_requestType.equals("Web")) {
					username = (String) request.getSession().getAttribute("username");
					if (username == null) {
						// Check whether this action is performed by a registered user. If not, the user is redirected to the login page.
						response.sendRedirect(response.encodeRedirectURL(request.getContextPath() + "/LoginPage.jsp"));
						return;
					}
				} else {
					username = request.getParameter("username");
				}
				sqlStatement = "UPDATE " + TableNames.STORIES_TABLE	+ " SET"
						+ " title = ?, location = ?, x_coord = ?, y_coord = ?, body = ?" + " WHERE s_id = ?";
				stmt = conn.prepareStatement(sqlStatement);
				
				stmt.setString(1, f_title);
				stmt.setString(2, f_locationDescription);
				stmt.setDouble(3, f_locationX);
				stmt.setDouble(4, f_locationY);
				stmt.setString(5, f_body);
				stmt.setInt(6, story_id);
				
				int databaseResponse = stmt.executeUpdate();

				boolean successStatus = false; // as default
				if (databaseResponse == 1) {
					successStatus = true;
				} else if (databaseResponse == 0) {
					successStatus = false;
				} else {
					// DO NOTHING!
				}
				
				if (f_requestType.equals("Android")) {
					JSONObject successStatusJsonObject = new JSONObject();
					try {
						successStatusJsonObject.put("success", successStatus);
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					out.print(successStatusJsonObject.toString());
				} else if (f_requestType.equals("Web")) {
					// After the operation is completed, redirect to main page.
					request.setAttribute("updateStorySuccess", successStatus);
					request.getRequestDispatcher("MainPage").forward(request, response);
				} else {
					// DO NOTHING!
				}
			} catch (SQLException e) {
				out.print(e.getMessage());
				e.printStackTrace();
			}
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
    }
    
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		processRequest(request, response);
	}

}
